package com.heisen.uua.configure;

import com.heisen.uua.filter.ValidateCodeFilter;
import com.heisen.uua.service.impl.XmUserDetailServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


/**
 * 用于处理/oauth开头的请求，Spring Cloud OAuth内部定义的获取令牌，
 * 刷新令牌的请求地址都是以/oauth/开头的，
 * 也就是说FebsSecurityConfigure用于处理和令牌相关的请求；
 */
@Order(2)  //。在Spring中，数字越小，优先级越高
@EnableWebSecurity  //开启了和Web相关的安全配置。
public class XmSecurityConfigure extends WebSecurityConfigurerAdapter {

    @Autowired
    private XmUserDetailServiceImpl userDetailService;

    @Autowired
    private ValidateCodeFilter validateCodeFilter;

    @Autowired
    private PasswordEncoder passwordEncoder;

//    /**
//     *  加密方式
//     * @return
//     */
//    @Bean
//    public PasswordEncoder passwordEncoder() {
//        return new BCryptPasswordEncoder();  //BCryptPasswordEncoder的特点就是，对于一个相同的密码，每次加密出来的加密串都不同：
//    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)
                .requestMatchers()
                .antMatchers("/oauth/**","/car/oauth/**")
                .and()
                .authorizeRequests()
                .antMatchers("/oauth/**","/car/oauth/**").authenticated()
                .and()
                .csrf().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailService).passwordEncoder(passwordEncoder);
    }

}
